package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import pac.Label;
import pac.Sql;
import pac.User;

import tools.KeyCheck;

public class Cancel extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setHeader("Content-Type", "text/html; charset=UTF-8");
		PrintWriter out = resp.getWriter();
		JSONObject jsonObject = new JSONObject();
		try {
			Label label = Sql
					.getLabel(Integer.parseInt(req.getParameter("id")));
			User user = Sql.getUser(Integer.parseInt(KeyCheck.getId(req)));

			JSONObject users = JSONObject.fromObject(label.joined_user);
			JSONArray userlist = users.getJSONArray("userList");
			for (int i = 0; i < userlist.size(); i++) {
				int user_id=userlist.getInt(i);
				if(user_id==user.id){
					userlist.remove(i);
					users=new JSONObject();
					users.put("userlist", userlist);
					label.joined_user=users.toString();
					Sql.editeLabel(label);
					
					JSONObject labels = JSONObject.fromObject(user.joined_label);
					JSONArray labelList = labels.getJSONArray("labelList");
					labelList.add(label.id);
					labels = new JSONObject();
					labels.put("labelList", labelList);
					user.joined_label=labels.toString();
					Sql.editeUser(user);
					
					jsonObject.put("errcode", 0);
					out.println(jsonObject);
					out.flush();
					out.close();
				}
			}
			

		} catch (Exception e) {
			jsonObject.put("errcode", 1);
			out.println(jsonObject);
			out.flush();
			out.close();
		}

	}
}
